package com.freedom.supercoin.base_library.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.freedom.supercoin.base_library.AppConst;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;
import java.util.UUID;


//import android.content.pm.IPackageStatsObserver;


/**
 * app 相关utils ,获取app包名, 等等
 */
public class AppUtil {
    private static final String LOG_TAG = AppUtil.class.getSimpleName();

    public static final int NO_APP = 0;
    public static final int SAME_APP = 1;
    public static final int HIGHER_VERSION = 2;
    public static final int LOWER_VERSION = 3;
    public static int VERSIONCODE = -1;

    /**
     * 检查是否安装某个应用
     *
     * @param context
     * @param packageName 包名
     * @return
     */
    public static boolean isInstalled(Context context, String packageName) {
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        for (PackageInfo packageInfo : packages) {
            if (TextUtils.equals(packageInfo.packageName, packageName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查是否安装对应应用
     *
     * @param context
     * @param packageName 包名
     * @param versionCode 版本号
     * @return (0表示应用未安装, 1表示相同版本, 2表示单前播放器版本大于传过来的版本号, 3表示单前播放器版本小于等于传过来的版本号)
     */
    public static int isInstalled(Context context, String packageName, int versionCode) {
        int contrastCode = 0;
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        for (PackageInfo packageInfo : packages) {
            if (TextUtils.equals(packageInfo.packageName, packageName)) {
                if (packageInfo.versionCode == versionCode) {
                    contrastCode = SAME_APP;
                } else {
                    // 单前版本大于传过来的版本号
                    if (packageInfo.versionCode > versionCode) {
                        Log.i(LOG_TAG, "Native Version is " + packageInfo.versionCode + " Higher " +
                                "than " + versionCode);
                        contrastCode = HIGHER_VERSION;
                    } else {// 单前版本小于等于传过来的版本号
                        Log.i(LOG_TAG, "Native Version is " + packageInfo.versionCode + " Lower " +
                                "than " + +versionCode);
                        contrastCode = LOWER_VERSION;
                    }
                    break;
                }
            }
        }
        return contrastCode;
    }

    public static int versionCodeByPkgName(Context context, String packageName) {
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        for (PackageInfo packageInfo : packages) {
            if (TextUtils.equals(packageInfo.packageName, packageName)) {
                return packageInfo.versionCode;
            }
        }
        return -1;
    }

    /**
     * 安装apk文件
     *
     * @param context
     * @param apkFile 文件
     */
    public static void install(Context context, File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() +
                    ".fileprovider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }


    /**
     * 卸载指定App
     *
     * @param context     上下
     * @param packageName 包名
     */
    public static void uninstall(Context context, String packageName) {
        Uri packageURI = Uri.parse("package:" + packageName);
        Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 验证apk文件是否损坏
     *
     * @param context
     * @param apkFile
     * @return
     */
    public static boolean isFullApk(Context context, File apkFile) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info;
        try {
            info = pm.getPackageArchiveInfo(apkFile.getAbsolutePath(), PackageManager
                    .GET_ACTIVITIES);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return info != null;
    }

    /**
     * 指定界面是否在前台
     *
     * @param context          上下文
     * @param listPlayActivity 指定页面容器
     */
    public static boolean isPlaying(Context context, List<String> listPlayActivity) {
        if (context == null) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (listPlayActivity.contains(cpn.getClassName())) {
                return true;
            }

        }
        return false;
    }

    /**
     * 获取本应用信息
     *
     * @param context
     * @return
     */
    public static PackageInfo getAppVersionInfo(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            return packageInfo;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过包名打开App应用
     *
     * @param context     上下文
     * @param packageName 要打开的App包名
     */
    public static void openApp(Context context, String packageName) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        context.startActivity(intent);
    }


    /**
     * Drawable对象转String
     * 多用于icon
     *
     * @param drawable
     * @return
     */
    public static String drawableToByte(Drawable drawable) {

        if (drawable != null) {
            Bitmap bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            int size = bitmap.getWidth() * bitmap.getHeight() * 4;

            // 创建一个字节数组输出流,流的大小为size
            ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
            // 设置位图的压缩格式，质量为100%，并放入字节数组输出流中
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            // 将字节数组输出流转化为字节数组byte[]
            byte[] imagedata = baos.toByteArray();

            String icon = Base64.encodeToString(imagedata, Base64.DEFAULT);
            return icon;
        }
        return null;
    }

    /**
     * 判断app是否为系统应用
     **/
    public static boolean isSystemApp(ApplicationInfo appInfo) {
        return (appInfo.flags & appInfo.FLAG_SYSTEM) > 0;
    }

    /**
     * 判断app是否为系统应用
     * uid是应用程序安装时由系统分配(1000 ～ 9999为系统应用程序保留)
     **/
    private static boolean isSystemApp(int uid) {
        return uid > 1000;
    }

    /**
     * 获取系统中的全部包信息
     *
     * @param context 应用上下文
     */
    public static void getPackageInfos(Context context) {

        PackageManager pm = context.getPackageManager();

        List<PackageInfo> packageInfos = pm.getInstalledPackages(0);

        for (PackageInfo packageInfo : packageInfos) {
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;
            String packageName = packageInfo.packageName;
            String appName = applicationInfo.loadLabel(pm).toString();

            if (isSystemApp(applicationInfo)) {
                Log.i(LOG_TAG, "系统应用:" + appName + "  包名:" + packageName);
            } else {
                Log.i(LOG_TAG, "安装应用:" + appName + "  包名:" + packageName);
            }
        }
    }

    /**
     * 获取系统中的全部包信息
     *
     * @param context 应用上下文
     */
    public static void getThirdAppInfo(Context context) {

        PackageManager pm = context.getPackageManager();

        List<PackageInfo> packageInfos = pm.getInstalledPackages(0);

        for (PackageInfo packageInfo : packageInfos) {
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;
            String packageName = packageInfo.packageName;
            String appName = applicationInfo.loadLabel(pm).toString();

            if (!isSystemApp(applicationInfo)) {

            }
        }
    }

    /**
     * 通过包名获取应用名称
     *
     * @param context     上下文
     * @param packageName 包名
     * @return 应用名称
     */
    public static String getAppName(Context context, String packageName) {
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, PackageManager
                    .GET_META_DATA);
            return applicationInfo.loadLabel(pm).toString();
//            return pm.getApplicationLabel(pm.getApplicationInfo(packageName, PackageManager
// .GET_META_DATA)).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "获取应用名失败";
    }

    public static int getAppVersionCode(Context context) {
        if (VERSIONCODE == -1) {
            try {
                PackageManager pm = context.getPackageManager();
                VERSIONCODE = pm.getPackageInfo(context.getPackageName(), PackageManager
                        .GET_META_DATA).versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return VERSIONCODE;
    }

    public static String getAppVersionName(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            return pm.getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA)
                    .versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String getFileNameForDownloadApk(String packageName, int versionCode) {
        return packageName + "_" + versionCode + ".apk";
    }

    public static String ReadInstallTime(Context context, String versionCode) {
        String JITVInstallTime = "JITVInstallTime_" + versionCode;
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        return sp.getString(JITVInstallTime, "0");
    }

    /**
     * 跳转系统应用详情设置页面的Intent
     */
    public static Intent getAppDetailSettingIntent(Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        return intent;
    }

    public static String getDeviceID() {
        String deviceId = SPUtils.getInstance().getString(AppConst.Keys.DEVICE_ID);
        if (TextUtils.isEmpty(deviceId)) {
             deviceId = NetUtils.getMac();
            if (TextUtils.equals(deviceId, "020000000000")) {
                deviceId = UUID.randomUUID().toString().replace("-", "");
            }
            if (!TextUtils.isEmpty(deviceId)) {
                deviceId = deviceId.replace(":", "");
            }
            SPUtils.getInstance().put(AppConst.Keys.DEVICE_ID,deviceId);
            return deviceId;
        } else {
            return deviceId;
        }
    }

}
